﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Bricks.BaseFramework.GenericForms;
using System.Reflection;
using Bricks.MiuiThemeMaker.BRMiuiThemeMaker;
using Bricks.MiuiThemeMaker.MiuiThemeMaker.Utility;
using Bricks.MiuiThemeMaker.OrmModel;
using Bricks.BaseFramework.Utility;
using System.Windows.Forms;

namespace Bricks.MiuiThemeMaker.MiuiThemeMaker
{
    /*********************************************************
     * 1.版权：积木工场 Bricks Factory
     * 2.作用：主窗体
     * 3.创建人：罗泽新
     * 4.创建日期：2012-04-28
     * 5.最后修改人：罗泽新
     * 6.最后修改日期：2012-06-28
     * 7.修改项目：
     * *******************************************************/
    public partial class MainWin : Window
    {
        private ZipBLL zipBll = new ZipBLL();
        private ElementBLL elementBll = new ElementBLL();

        public MainWin()
        {
            InitializeComponent();
            LoadAssemblyInfo();  //加载声明信息
            //LoadTest();
            //LoadTree();
            LoadParentPreview();  //加载预览图（父级）
        }

        /// <summary>
        /// 加载预览图（父级）
        /// </summary>
        private void LoadParentPreview()
        {
            List<BF_Element> parents = elementBll.GetParentPreviewList(SystemData.Instance.DBType);
            foreach (BF_Element parent in parents)
            {
                TabItem newItem = new TabItem();
                newItem.DataContext = parent;
                newItem.Header = parent.Name;
                tabParentPreview.Items.Add(newItem);
            }

            //From FibreCheck参考：单位管理
            //TabItem newItem = new TabItem();
            //newItem.DataContext = mailSetting;
            //MailReportSettingPanel settingPanel = new MailReportSettingPanel();
            //SetMailReportSettingPanelData(mailSetting, settingPanel);
            //newItem.Content = settingPanel;

            ////绑定
            //Binding headerBinding = new Binding("DepartmentName");
            //headerBinding.Source = mailSetting;
            //headerBinding.Converter = new MailSettingDepartmentNameConverter();
            //headerBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            //newItem.SetBinding(TabItem.HeaderProperty, headerBinding);

            //tabMailSetting.Items.Add(newItem);
        }

        /// <summary>
        /// 加载树
        /// </summary>
        private void LoadTree()
        {
            //this.tvElement.ItemsSource = null;
            //this.tvElement.Items.Clear();
            //this.tvElement.ItemsSource = elementBll.GetElementTree(SystemData.Instance.DBType);
        }

        /// <summary>
        /// 树节点切换事件（当是文件的时候，则需要对相关图片进行显示或者切换）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvElement_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            ElementNode node = this.tvElement.SelectedItem as ElementNode;
            if (node == null)
                return;

            //如果是文件
            if (node.Element.Type == 3)
            {
                //完整绝对路径
                string fullPath = System.IO.Path.Combine(SystemData.Instance.ThemePath, elementBll.GetFullPath(node, SystemData.Instance.DBType));

                //中间编辑部分
                this.imgOriginal.Source = ImageConverter.ConvertToImage(fullPath);  //原来的图片

                //右边预览图部分
                Image previewImage = FindImage(node.Element.ID);
                //选中预览图Grid中的Image
            }
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private Image FindImage(Guid id)
        {
            Image result = new Image();
            return result;
        }

        /// <summary>
        /// 加载测试（仅用于开发期间的测试）
        /// </summary>
        private void LoadTest()
        {
            Image img = new Image();
            BitmapImage biTitle = new BitmapImage();
            biTitle.BeginInit();
            biTitle.UriSource = new Uri("/MiuiThemeMaker;component/Images/xmsale_loginBg.gif", UriKind.Relative);
            biTitle.EndInit();
            img.Stretch = Stretch.Fill;
            img.Source = biTitle;
            img.Tag = "1";
            UiUtility.AddToGrid(this.gridView, img);

            img = new Image();
            img.Stretch = Stretch.Fill;
            img.Source = biTitle;
            img.Width = 50;
            img.Height = 50;
            img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            img.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            Thickness tn = new Thickness(80, 10, 0, 0);
            img.Margin = tn;
            img.Tag = "2";
            UiUtility.AddToGrid(this.gridView, img);

            img = new Image();
            img.Stretch = Stretch.Fill;
            img.Source = biTitle;
            img.Width = 50;
            img.Height = 50;
            img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            img.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            tn = new Thickness(80, 70, 0, 0);
            img.Margin = tn;
            img.Tag = "3";
            UiUtility.AddToGrid(this.gridView, img);

            img = new Image();
            img.Stretch = Stretch.Fill;
            img.Source = biTitle;
            img.Width = 50;
            img.Height = 50;
            img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            img.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            tn = new Thickness(80, 130, 0, 0);
            img.Margin = tn;
            img.Tag = "4";
            UiUtility.AddToGrid(this.gridView, img);

            //测试移除
            UiUtility.RemoveFromGrid(this.gridView, img);

            img = new Image();
            img.Stretch = Stretch.Fill;
            img.Source = biTitle;
            img.Width = 50;
            img.Height = 50;
            img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            img.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            tn = new Thickness(140, 130, 0, 0);
            img.Margin = tn;
            img.Tag = "5";
            UiUtility.AddToGrid(this.gridView, img);

            foreach (var item in this.gridView.Children)
            {
                if (item is Image)
                {
                    (item as Image).MouseLeftButtonUp += new MouseButtonEventHandler(MainWin_MouseLeftButtonUp);
                }
            }
        }

        void MainWin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = (sender as Image);
            MsgBox.Show(img.Tag.ToString());
        }

        /// <summary>
        /// 加载声明信息
        /// </summary>
        private void LoadAssemblyInfo()
        {
            string title = String.Format("{0} V{1} {2}", AssemblyInfo.Instance.AssemblyTitle, AssemblyInfo.Instance.AssemblyVersion, "Beta");
            this.titleBar.Title = title;

            this.tbStatus.Text = "欢迎使用MIUI主题制作工具";
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miNew_Click(object sender, RoutedEventArgs e)
        {
            //1.基于基础主题MIUI-Original.MTZ解压

            //2.直接将主题解压到安装目录下的临时文件夹（以日期命名）【首选方案】（可修改为可选择V2和V4基础主题）
            #region 直接将主题解压到安装目录下的临时文件夹（以日期命名）【首选方案】
            string baseMTZPath = System.IO.Path.Combine(SystemData.Instance.BaseDirectory, "BaseData", SystemData.Instance.BaseV2MTZ);  //构造基础MTZ-V2完整路径
            string tempMTZPath = System.IO.Path.Combine(SystemData.Instance.BaseDirectory, "TempThemes", DateTime.Now.ToString("yyyyMMddHHmmss"));  //构建临时MTZ完整路径
            ZipBLL.UnZip(baseMTZPath, tempMTZPath, null);  //解压到临时路径
            #endregion

            //2.选择目标文件夹，创建新的文件夹，并打开主题【备选方案】
            #region 选择目标文件夹，创建新的文件夹，并打开主题【备选方案】
            //FolderBrowserDialog dialog = new FolderBrowserDialog();
            //if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    //解压到指定文件夹
            //    string baseMTZPath = System.IO.Path.Combine(SystemData.Instance.BaseDirectory, "BaseData", SystemData.Instance.BaseMTZ);  //构造基础MTZ完整路径
            //    ZipBLL.UnZip(baseMTZPath, dialog.SelectedPath, null);

            //    //将目录写入到SystemData中
            //    SystemData.Instance.ThemePath = dialog.SelectedPath;
            //}
            #endregion
        }

        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miOpen_Click(object sender, RoutedEventArgs e)
        {
            //1.可直接打开MTZ，打开后解压
            //2.可直接打开主题文件夹
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miSave_Click(object sender, RoutedEventArgs e)
        {
            //将现有项目保存为某种特定格式（工具特有格式）

            MsgBox.Show("保存");
        }

        /// <summary>
        /// 另存为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miSaveAs_Click(object sender, RoutedEventArgs e)
        {
            //选择路径，另存为另外一个主题文件夹
            //此处不另存为MTZ，MTZ可直接导出
        }

        /// <summary>
        /// 输出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miOutput_Click(object sender, RoutedEventArgs e)
        {
            //输出到
        }

        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miRevoke_Click(object sender, RoutedEventArgs e)
        {
            //撤销上一步操作
        }

        /// <summary>
        /// 历史
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miHistory_Click(object sender, RoutedEventArgs e)
        {
            //查看历史修改记录
        }

        /// <summary>
        /// 重做/取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miCancel_Click(object sender, RoutedEventArgs e)
        {
            //撤销所有更改，回到原始状态
        }

        /// <summary>
        /// 帮助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miHelp_Click(object sender, RoutedEventArgs e)
        {
            //帮助文档
            //关于
            ShowAbout();
        }

        /// <summary>
        /// 关于
        /// </summary>
        private void ShowAbout()
        {
            AboutWin win = new AboutWin();
            win.Owner = this;
            win.ShowDialog();
        }

        /// <summary>
        /// 米世界
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miMi_Click(object sender, RoutedEventArgs e)
        {
            //小米
            //MIUI
            //米聊
        }

        /// <summary>
        /// 9.PNG编辑器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mi9Png_Click(object sender, RoutedEventArgs e)
        {
            //跳转到外部9.PNG编辑器
        }

        /// <summary>
        /// 压缩测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void miZip_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        //string err = string.Empty;
        //        //bll.ZipFile(@"c:\c", string.Empty, out err);

        //        ZipBLL.Zip(@"c:\c\", @"c:\zip.mtz", string.Empty);  //Add By Northow：如果写c:\c会将c作为根目录压缩进去，如果写c:\c\则不会
        //        MsgBox.Show("压缩成功！");
        //    }
        //    catch (Exception ex)
        //    {
        //        MsgBox.ShowAlert(ex.Message);
        //    }
        //}

        /// <summary>
        /// 解压测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void miUnZip_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        //string err = string.Empty;
        //        //bll.UnZipFile(@"C:\c.mtz", string.Empty, out err);

        //        ZipBLL.UnZip(@"c:\c.mtz", @"c:\unZip", string.Empty);
        //        MsgBox.Show("解压成功！");
        //    }
        //    catch (Exception ex)
        //    {
        //        MsgBox.ShowAlert(ex.Message);
        //    }
        //}

        /// <summary>
        /// 关闭确认
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (MsgBox.ShowQuestion("确定退出工具？") != MessageBoxResult.Yes)
                e.Cancel = true;
            else
                base.OnClosing(e);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //BF_Element data = new BF_Element();
                //data.Name = "首页";
                //data.Type = 1;
                //data.Difficulty = 1;
                //data.Remark = "首页";
                //data.OrderNo = 1;
                //elementBll.AddElement(data, SystemData.Instance.DBType);

                //data = new BF_Element();
                //data.Name = "电话";
                //data.Type = 1;
                //data.Difficulty = 1;
                //data.Remark = "电话";
                //data.OrderNo = 2;
                //elementBll.AddElement(data, SystemData.Instance.DBType);

                //data = new BF_Element();
                //data.Name = "短信";
                //data.Type = 1;
                //data.Difficulty = 1;
                //data.Remark = "短信";
                //data.OrderNo = 3;
                //elementBll.AddElement(data, SystemData.Instance.DBType);

                //data = new BF_Element();
                //data.Name = "联系人";
                //data.Type = 1;
                //data.Difficulty = 1;
                //data.Remark = "联系人";
                //data.OrderNo = 3;
                //elementBll.AddElement(data, SystemData.Instance.DBType);

                //data = new BF_Element();
                //data.Name = "通知栏";
                //data.Type = 1;
                //data.Difficulty = 1;
                //data.Remark = "通知栏";
                //data.OrderNo = 3;
                //elementBll.AddElement(data, SystemData.Instance.DBType);

                //MsgBox.Show("新增成功");
            }
            catch (Exception ex)
            {
                MsgBox.ShowAlert(ex.Message);
            }
        }

        /// <summary>
        /// 元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miElement_Click(object sender, RoutedEventArgs e)
        {
            ElementWin window = new ElementWin();
            window.ShowDialog();
        }
    }
}
